package com.spn.blog.article.service;

import com.alibaba.fastjson.JSON;
import com.spn.blog.common.dao.pojo.Article;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;


@Service
public class ESservice {

    @Value("${es.index}")
    private String index;
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * @param id  ES文档 id
     * @param obj  需要修改的对象值
     * @param <T>
     * @return
     * @throws IOException
     */
    public <T> boolean addOrUpdates(String id, T obj) throws IOException {

        GetRequest getRequest = new GetRequest(index, id);
        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        String sourceAsString = documentFields.getSourceAsString();
        if (sourceAsString == null) {
            // 添加

            // 获取索引
            IndexRequest indexRequest = new IndexRequest(index)
                    .id(id)
                    .timeout(TimeValue.timeValueSeconds(1))
                    .timeout("1s");

            //吧对象转换为json存储
            indexRequest.source(JSON.toJSONString(obj), XContentType.JSON);

            //发送请求,获取响应结果
            IndexResponse response = null;

            try {
                response = client.index(indexRequest, RequestOptions.DEFAULT);

            } catch (IOException e) {
                // 异常处理
                String message = e.getMessage();
                boolean contains = message.contains("response=HTTP/1.1 200 OK");
                if (contains){
                    System.out.println("response=HTTP/1.1 200 OK");
                } else if (message.contains("response=HTTP/1.1 201 OK")) {
                    System.out.println("response=HTTP/1.1 201 OK");
                }
            }
        } else {
            // 更新
            UpdateRequest updateRequest = new UpdateRequest(index, id);
            updateRequest.timeout("1s");// 设置请求时间，超过1s就不执行了
            updateRequest.doc(JSON.toJSONString(obj), XContentType.JSON);
            client.update(updateRequest, RequestOptions.DEFAULT);
        }

        return true;
    }


    /**
     *
     * @param objs 我们需要转移的对象数组
     * @param <T>
     * @return
     * @throws IOException
     */
    public <T> Boolean cpOnEs(List<T> objs) throws IOException {

        // 先删除原来的
        GetIndexRequest getIndexRequest = new GetIndexRequest(index);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (exists) {
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
            AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            System.out.println("索引删除状态：" + delete.isAcknowledged());
        }

        // 创建索引
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        createIndexRequest.settings(Settings.builder().put("index.number_of_shards", 3) // 分片数
                .put("index.number_of_replicas", 1) // 副本数
                .put("analysis.analyzer.default.tokenizer", "ik_max_word") // 设置默认分词器
        );
        client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

        exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (!exists) return false;
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        for (T obj : objs) {
            bulkRequest.add(new IndexRequest(index)
                    // 这里做了一个强转，这个方法只适合Article的
                    .id(((Article)obj).getId())
                    .source(JSON.toJSONString(obj), XContentType.JSON)
            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        return true;
    }

}
